home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_09_08 / 9n08100b < prev    next >
Text File  |  1991-06-04  |  2KB  |  82 lines

  1. #include <string.h>  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include <alloc.h>  
  5. #include <ctype.h>     
  6. char *test_str = 
  7.    "This is a string  with a number   \tof words in\nit to test"
  8.    " the string word parsing function."     
  9.    /* Note that the string includes words separated by multiple spaces, 
  10.    as well as newlines and tabs.    */
  11.  
  12. int wordcount(char *str)
  13.    {       
  14.    int count = 0;       
  15.    char *s;       
  16.    s=str;       
  17.    while(*s && isspace(*s))s++; //Skip leading spaces       
  18.    while(*s)
  19.        {  
  20.       while(*s && !isspace(*s))
  21.            s++;  //Skip over the word  
  22.       while(*s && isspace(*s))
  23.            s++; //Skip over all whitespace  
  24.        count++;  //Increment count - Note it starts as 0 not 1       
  25.        }       
  26.    return(count);  
  27.    }
  28.  
  29. void str_to_ptrarray(char *orgstr, char *ptrarray[])
  30.    {
  31.    int i=0;       
  32.    char *s;       
  33.    s=orgstr;       
  34.    while(*s && isspace(*s))
  35.        s++; //Leading white space       
  36.    while(*s)
  37.        {  
  38.        ptrarray[i]=s;      //assign it  
  39.        i++;  
  40.        while(*s && !isspace(*s))
  41.            s++; //skip over the word  
  42.        while(*s && isspace(*s))
  43.            {  //skip over the whitespace  
  44.            *s=0; //terminate the string  
  45.            s++;  
  46.            }
  47.        }
  48.    }  
  49.  
  50. int allocate_space(int nbr, char ***ptrarray, int size, char **string)
  51.    {       
  52.    //Allocate the array pointers       
  53.    if( (*ptrarray= (char **)calloc(nbr,sizeof(char *))) ==NULL)
  54.        return(0);       //Allocate the string space       
  55.    if( (*string = (char *)calloc(size+1,sizeof(char))) == NULL)
  56.        return(0);       
  57.    return(1);  
  58.    }
  59.  
  60. void free_space(char ***ptrarray, char **string)
  61.    {
  62.    free(*ptrarray);       
  63.    free(*string);  
  64.    }     
  65.  
  66. void main(void)
  67.    {       
  68.    char **ptrarray;       
  69.    char *strg;  
  70.    int wordcnt;       
  71.    int size;          
  72.    size = strlen(test_str);       
  73.    wordcnt=wordcount(test_str);       
  74.    allocate_space(wordcnt,&ptrarray,size,&strg);       
  75.    strcpy(strg,test_str);       
  76.    str_to_ptrarray(strg,ptrarray);          
  77.    for(size = 0;size < wordcnt;size++)  
  78.        printf("%s:n",ptrarray[size]);
  79.    free_space(&ptrarray,&strg);  
  80.    }
  81.  
  82.